package com.topjia.music.request.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.topjia.music.request.entity.album.Album;
import com.topjia.music.request.entity.disst.Disst;
import com.topjia.music.request.entity.singer.Singer;
import com.topjia.music.request.entity.song.Song;
import com.topjia.music.request.entity.video.Video;
import com.topjia.music.request.service.SearchService;
import com.topjia.music.request.util.HandleReqData;
import com.topjia.music.request.util.RequestHeader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wjh
 * @date 2019-12-20 15:03
 */
@Service
@Slf4j
@RefreshScope
public class SearchServiceImpl implements SearchService {

    @Value("${music.cookie}")
    private String cookie;

    @Override
    public Map<String, Object> search(String reqData, String type) throws Exception {
        RequestHeader header = new RequestHeader("", "", cookie);
        JSONObject result = (JSONObject) HandleReqData.sendPostRequest(reqData, header);
        log.info("{}", result);
        Map<String, Object> res = new HashMap<>();
        switch (type) {
            case "0": {
                res = handleSearchSongData(result);
                break;
            }
            case "4": {
                res = handleSearchVideoData(result);
                break;
            }
            case "2": {
                res = handleSearchAlbumData(result);
                break;
            }
            case "3": {
                res = handleSearchSongListData(result);
                break;
            }
            case "7": {
                res = handleSearchLyricData(result);
                break;
            }
            case "9": {
                res = handleSearchSingerData(result);
                break;
            }
        }
        return res;
    }

    private Map<String, Object> handleSearchSingerData(JSONObject result) {
        HashMap<String, Object> res = new HashMap<>();
        String message = result.getString("message");
        if (message.equals("no results")) {
            res.put("message", "no_results");
            res.put("singerTotalnum", 0);
        } else if (message.equals("system error")) {
            res.put("message", "QQ音乐服务器错误");
            res.put("singerTotalnum", 0);
        } else {
            JSONObject singerListInfo = result.getJSONObject("data").getJSONObject("singer");
            // 处理基本数据
            res.put("curnum", singerListInfo.getInteger("curnum"));
            res.put("curpage", singerListInfo.getInteger("curpage"));
            res.put("singerTotalnum", singerListInfo.getInteger("totalnum"));
            // 歌手处理
            JSONArray singerJsonList = singerListInfo.getJSONArray("list");
            ArrayList<Singer> singers = new ArrayList<>();
            singerJsonList.forEach((item) -> {
                JSONObject singerJsonObj = (JSONObject) item;
                Singer singer = Singer.builder()
                        .singerId(singerJsonObj.getInteger("singerID"))
                        .SingerMid(singerJsonObj.getString("singerMID"))
                        .SingerName(singerJsonObj.getString("singerName"))
                        .SingerPic(singerJsonObj.getString("singerPic"))
                        .build();
                singers.add(singer);
            });
            res.put("singer", singers);
            res.put("message", "success");
        }
        return res;
    }

    private Map<String, Object> handleSearchLyricData(JSONObject result) {
        HashMap<String, Object> res = new HashMap<>();
        Integer code = result.getInteger("code");
        if (code.compareTo(0) != 0) {
            res.put("message", "QQ音乐服务器错误");
            res.put("lyricTotalnum", 0);
        } else {
            JSONObject lyricListInfo = result.getJSONObject("req_1").getJSONObject("data").getJSONObject("body").getJSONObject("song");
            JSONObject metaInfo = result.getJSONObject("req_1").getJSONObject("data").getJSONObject("meta");
            // 处理基本数据
            // 处理基本数据
            res.put("curnum", metaInfo.getInteger("ein"));
            res.put("curpage", metaInfo.getInteger("curpage"));
            res.put("lyricTotalnum", metaInfo.getInteger("estimate_sum"));
            // 歌词处理
            JSONArray lyricList = lyricListInfo.getJSONArray("list");
            res.put("showData", lyricList);
            // 处理歌词结果的歌曲信息
            ArrayList<Song> songs = new ArrayList<>();
            lyricList.forEach(item -> {
                JSONObject songJSON = (JSONObject) item;
                Song song = new Song();
                song.setId(songJSON.getString("id"));
                song.setMid(songJSON.getString("mid"));
                song.setName(songJSON.getString("name"));
                JSONArray singers = songJSON.getJSONArray("singer");
                ArrayList<Singer> singerArrayList = new ArrayList<>();
                for (Object singero : singers) {
                    JSONObject singerObj = (JSONObject) singero;
                    Singer singer = new Singer();
                    singer.setSingerId(singerObj.getInteger("id"));
                    singer.setSingerMid(singerObj.getString("mid"));
                    singer.setSingerName(singerObj.getString("name"));
                    singer.setSingerPic("https://y.gtimg.cn/music/photo_new/T001R300x300M000" + singerObj.getString("mid") + ".jpg?max_age=2592000");
                    singerArrayList.add(singer);
                }
                song.setSingers(singerArrayList);
                JSONObject album = songJSON.getJSONObject("album");
                if (album != null) {
                    song.setAlbum(album.getString("name"));
                    song.setImage("https://y.gtimg.cn/music/photo_new/T002R500x500M000" + album.getString("mid") + ".jpg?max_age=2592000");
                }
                song.setDuration(songJSON.getString("interval"));
                songs.add(song);
            });
            res.put("songs", songs);
            res.put("message", "success");
        }
        return res;
    }

    private Map<String, Object> handleSearchSongListData(JSONObject result) {
        HashMap<String, Object> res = new HashMap<>();
        Integer code = result.getInteger("code");
        if (code.compareTo(0) != 0) {
            res.put("message", "QQ音乐服务器错误");
            res.put("disstsTotalnum", 0);
        } else {
            JSONObject songListInfo = result.getJSONObject("req_1").getJSONObject("data").getJSONObject("body").getJSONObject("songlist");
            JSONObject metaInfo = result.getJSONObject("req_1").getJSONObject("data").getJSONObject("meta");
            // 处理基本数据
            res.put("curnum", metaInfo.getInteger("ein"));
            res.put("curpage", metaInfo.getInteger("curpage"));
            res.put("disstsTotalnum", metaInfo.getInteger("estimate_sum"));
            // 歌单处理
            JSONArray songListJsonList = songListInfo.getJSONArray("list");
            ArrayList<Disst> dissts = new ArrayList<>();
            songListJsonList.forEach((item) -> {
                JSONObject songListJsonObj = (JSONObject) item;
                Disst disst = Disst.builder()
                        .disstId(songListJsonObj.getString("dissid"))
                        .disstName(songListJsonObj.getString("dissname"))
                        .visitnum(songListJsonObj.getInteger("listennum"))
                        .disstLogo(songListJsonObj.getString("imgurl"))
                        .nickname(songListJsonObj.getJSONObject("creator").getString("name"))
                        .songNum(songListJsonObj.getInteger("song_count"))
                        .desc(songListJsonObj.getString("introduction"))
                        .build();
                dissts.add(disst);
            });
            res.put("dissts", dissts);
            res.put("message", "success");
        }
        return res;
    }

    private Map<String, Object> handleSearchAlbumData(JSONObject result) {
        HashMap<String, Object> res = new HashMap<>();
        Integer code = result.getInteger("code");
        if (code.compareTo(0) != 0) {
            res.put("message", "QQ音乐服务器错误");
            res.put("albumsTotalnum", 0);
        } else {
            JSONObject albumInfo = result.getJSONObject("req_1").getJSONObject("data").getJSONObject("body").getJSONObject("album");
            JSONObject metaInfo = result.getJSONObject("req_1").getJSONObject("data").getJSONObject("meta");
            // 处理基本数据
            res.put("curnum", metaInfo.getInteger("ein"));
            res.put("curpage", metaInfo.getInteger("curpage"));
            res.put("albumsTotalnum", metaInfo.getInteger("estimate_sum"));
            // 专辑处理
            JSONArray albumJsonList = albumInfo.getJSONArray("list");
            ArrayList<Album> albums = new ArrayList<>();
            albumJsonList.forEach((item) -> {
                JSONObject albumJsonObj = (JSONObject) item;
                // 处理歌手
                ArrayList<Singer> singers = new ArrayList<>();
                JSONArray singersJSONArr = albumJsonObj.getJSONArray("singer_list");
                singersJSONArr.forEach((singerObj) -> {
                    JSONObject singerJSONObj = (JSONObject) singerObj;
                    Singer singer = new Singer();
                    singer.setSingerId(singerJSONObj.getInteger("id"));
                    singer.setSingerMid(singerJSONObj.getString("mid"));
                    singer.setSingerName(singerJSONObj.getString("name"));
                    singer.setSingerPic("https://y.gtimg.cn/music/photo_new/T001R300x300M000" + singerJSONObj.getString("mid") + ".jpg?max_age=2592000");
                    singers.add(singer);
                });

                Album album = Album.builder()
                        .id(albumJsonObj.getInteger("albumID"))
                        .mid(albumJsonObj.getString("albumMID"))
                        .name(albumJsonObj.getString("albumName"))
                        .image(albumJsonObj.getString("albumPic"))
                        .pubTime(albumJsonObj.getString("publicTime"))
                        .currentSongNum(albumJsonObj.getInteger("song_count"))
                        .singers(singers)
                        .build();
                albums.add(album);
            });
            res.put("albums", albums);
            res.put("message", "success");
        }
        return res;
    }

    private Map<String, Object> handleSearchVideoData(JSONObject result) {
        HashMap<String, Object> res = new HashMap<>();
        Integer code = result.getInteger("code");
        if (code.compareTo(0) != 0) {
            res.put("message", "QQ音乐服务器错误");
            res.put("videosTotalnum", 0);
        } else {
            JSONObject MvInfo = result.getJSONObject("req_1").getJSONObject("data").getJSONObject("body").getJSONObject("mv");
            JSONObject metaInfo = result.getJSONObject("req_1").getJSONObject("data").getJSONObject("meta");
            // 处理基本数据
            res.put("curnum", metaInfo.getInteger("ein"));
            res.put("curpage", metaInfo.getInteger("curpage"));
            res.put("videosTotalnum", metaInfo.getInteger("estimate_sum"));
            // MV处理
            JSONArray mvJsonList = MvInfo.getJSONArray("list");
            ArrayList<Video> videos = new ArrayList<>();
            mvJsonList.forEach((item) -> {
                JSONObject mvJsonObj = (JSONObject) item;
                // 处理歌手
                ArrayList<Singer> singers = new ArrayList<>();
                JSONArray singersJSONArr = mvJsonObj.getJSONArray("singer_list");
                singersJSONArr.forEach((singerObj) -> {
                    JSONObject singerJSONObj = (JSONObject) singerObj;
                    Singer singer = new Singer();
                    singer.setSingerId(singerJSONObj.getInteger("id"));
                    singer.setSingerMid(singerJSONObj.getString("mid"));
                    singer.setSingerName(singerJSONObj.getString("name"));
                    singer.setSingerPic("https://y.gtimg.cn/music/photo_new/T001R300x300M000" + singerJSONObj.getString("mid") + ".jpg?max_age=2592000");
                    singers.add(singer);
                });

                Video video = Video.builder()
                        .mvId(mvJsonObj.getInteger("mv_id"))
                        .vid(mvJsonObj.getString("v_id"))
                        .singers(singers)
                        .createTime(mvJsonObj.getString("publish_date"))
                        .listenNum(mvJsonObj.getInteger("play_count"))
                        .mvPicUrl(mvJsonObj.getString("mv_pic_url"))
                        .mvTitle(mvJsonObj.getString("mv_name"))
                        .duration(mvJsonObj.getInteger("duration"))
                        .build();
                videos.add(video);
            });
            res.put("videos", videos);
            res.put("message", "success");
        }
        return res;
    }

    private Map<String, Object> handleSearchSongData(JSONObject getRes) {
        HashMap<String, Object> res = new HashMap<>();
        Integer code = getRes.getInteger("code");
        if (code.compareTo(0) != 0) {
            res.put("message", "QQ音乐服务器错误");
            res.put("songListTotalnum", 0);
        } else {
            JSONObject songInfo = getRes.getJSONObject("req_1").getJSONObject("data").getJSONObject("body").getJSONObject("song");
            JSONObject metaInfo = getRes.getJSONObject("req_1").getJSONObject("data").getJSONObject("meta");
            // 处理基本数据
            res.put("curnum", metaInfo.getInteger("ein"));
            res.put("curpage", metaInfo.getInteger("curpage"));
            res.put("songListTotalnum", metaInfo.getInteger("estimate_sum"));
            // 处理歌曲和高亮字体
            JSONArray songArr = songInfo.getJSONArray("list");
            ArrayList<Song> songs = new ArrayList<>();
            ArrayList<Object> hiLights = new ArrayList<>();
            songArr.forEach(item -> {
                HashMap<String, Object> hiLight = new HashMap<>();
                // 歌曲
                Song song = new Song();
                JSONObject songJSON = (JSONObject) item;
                song.setId(String.valueOf(songJSON.getInteger("id")));
                song.setMid(songJSON.getString("mid"));
                song.setName(songJSON.getString("name"));
                song.setSubTitle(songJSON.getJSONObject("album").getString("subtitle"));
                song.setMediaMid(songJSON.getJSONObject("file").getString("media_mid"));
                song.setTitle(songJSON.getString("title"));
                JSONArray singers = songJSON.getJSONArray("singer");
                ArrayList<Singer> singerArrayList = new ArrayList<>();
                ArrayList<HashMap<String, String>> singerHiLight = new ArrayList<>();
                for (Object singero : singers) {
                    JSONObject singerObj = (JSONObject) singero;
                    Singer singer = new Singer();
                    HashMap<String, String> singerNameHiLight = new HashMap<>();
                    singer.setSingerId(singerObj.getInteger("id"));
                    singer.setSingerMid(singerObj.getString("mid"));
                    singer.setSingerName(singerObj.getString("name"));
                    singer.setSingerPic("https://y.gtimg.cn/music/photo_new/T001R300x300M000" + singerObj.getString("mid") + ".jpg?max_age=2592000");
                    singerArrayList.add(singer);
                    singerNameHiLight.put("singer_name_hiLight", singerObj.getString("title_hilight"));
                    singerNameHiLight.put("singer_name", singer.getSingerName());
                    singerHiLight.add(singerNameHiLight);
                }
                song.setSingers(singerArrayList);
                String album = songJSON.getJSONObject("album").getString("name");
                if (!StringUtils.isEmpty(album)) {
                    song.setAlbum(album);
                    song.setImage("https://y.gtimg.cn/music/photo_new/T002R500x500M000" + songJSON.getJSONObject("album").getString("mid") + ".jpg?max_age=2592000");
                }
                song.setDuration(String.valueOf(songJSON.getInteger("interval")));
                songs.add(song);
                // 高亮
                hiLight.put("singer_hilight", singerHiLight);
                hiLight.put("songname_hilight", songJSON.getString("title_hilight"));
                hiLight.put("albumname_hilight", songJSON.getJSONObject("album").getString("title_hilight"));
                hiLight.put("song_name", song.getName());
                hiLight.put("song_subtitle", song.getSubTitle());
                hiLight.put("song_album", song.getAlbum());
                hiLight.put("duration", song.getDuration());
                hiLights.add(hiLight);
            });
            res.put("songList", songs);
            res.put("hiLights", hiLights);
            // 处理直达歌手
            JSONObject zhida = getRes.getJSONObject("req_1").getJSONObject("data").getJSONObject("body").getJSONObject("zhida");
            if (zhida != null) {
                JSONArray zhidaJSONArray = zhida.getJSONArray("list");
                if (!CollectionUtils.isEmpty(zhidaJSONArray)) {
                    Object zhida_singer_obj = zhidaJSONArray.get(0);
                    if (zhida_singer_obj != null) {
                        JSONObject zhida_singer = (JSONObject) zhida_singer_obj;
                        JSONObject customInfo =  zhida_singer.getJSONObject("custom_info");
                        HashMap<String, Object> zhidaMap = new HashMap<>();
                        try {
                            zhidaMap.put("mvNum", Integer.parseInt(customInfo.getString("mv_num")));
                            zhidaMap.put("albumNum", Integer.parseInt(customInfo.getString("album_num")));
                            zhidaMap.put("songNum", Integer.parseInt(customInfo.getString("song_num")));
                            Singer singer = new Singer();
                            singer.setSingerId(Integer.parseInt(zhida_singer.getString("id")));
                            singer.setSingerName(zhida_singer.getString("title"));
                            singer.setSingerMid(customInfo.getString("mid"));
                            singer.setSingerPic("https://y.gtimg.cn/music/photo_new/T001R300x300M000" + customInfo.getString("mid") + ".jpg?max_age=2592000");
                            zhidaMap.put("singer", singer);
                            res.put("zhida", zhidaMap);
                        } catch (Exception e) {
                            res.put("zhida", null);
                        }
                    } else {
                        res.put("zhida", null);
                    }
                } else {
                    res.put("zhida", null);
                }
            } else {
                res.put("zhida", null);
            }
            res.put("message", "success");
        }
        return res;
    }
}
